const sqlite3 = require('sqlite3').verbose();

class Database {
  constructor() {
    this.db = null;
  }

  /**
   * Initialize the database connection
   * @param {string} dbPath - Path to the SQLite database file
   */
  init(dbPath) {
    this.db = new sqlite3.Database(dbPath, err => {
      if (err) {
        console.error('Error opening database:', err.message);
      } else {
        console.log('Connected to the SQLite database.');
      }
    });
  }

  /**
   * Close the database connection
   */
  close() {
    if (this.db) {
      this.db.close(err => {
        if (err) {
          console.error('Error closing database:', err.message);
        } else {
          console.log('Database connection closed.');
        }
      });
    }
  }

  /**
   * Run a query that doesn't return rows
   * @param {string} sql - SQL query to execute
   * @param {Array} params - Parameters for the SQL query
   * @returns {Promise} - Promise that resolves when the query is complete
   */
  run(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.run(sql, params, function (err) {
        if (err) {
          reject(err);
        } else {
          resolve({ id: this.lastID, changes: this.changes });
        }
      });
    });
  }

  /**
   * Get a single row from the database
   * @param {string} sql - SQL query to execute
   * @param {Array} params - Parameters for the SQL query
   * @returns {Promise} - Promise that resolves with the row data
   */
  get(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.get(sql, params, (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  /**
   * Get all rows from the database
   * @param {string} sql - SQL query to execute
   * @param {Array} params - Parameters for the SQL query
   * @returns {Promise} - Promise that resolves with the rows data
   */
  all(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.all(sql, params, (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }
}

module.exports = Database;
